import request from '@/packages/axios';

interface IEventSource {
    onSuccess: (answer: string) => void;
    onUpdate: (answer: string) => void;
    onError: (error: any) => void;
    url?: string; 
}

class DeepseekApis {

    question(question: string) {
        return request({ url: '/deepseek/question', method: 'post', data: { question }, timeout: 30000 })
    }
    
    rag(question: string) {
        return request({ url: '/deepseek/rag', method: 'post', data: { question }, timeout: 30000 })
    }
    
    tools(question: string) {
        return request({ url: '/deepseek/tools', method: 'post', data: { question }, timeout: 30000 })
    }

    addRagData(url: string) {
        return request({ url: '/deepseek/add-rag-data', method: 'post', data: { url }, timeout: 30000  })
    }


    eventSource({ onSuccess, onError, onUpdate, url = '/api/deepseek/stream' }: IEventSource) {
        const eventSource = new EventSource(url);
        eventSource.onmessage = ({ data }) => {
            const { answer, end } = JSON.parse(data);
            if (!end) {
                onUpdate(answer);
                return;
            } else {
                onSuccess(answer);
                eventSource.close();
            }
        };
        eventSource.onerror = (error) => {
            onError(error);
            eventSource.close();
        };
    };

}
export default DeepseekApis;